<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索🔍">
        <el-input placeholder="请输入职位的关键字" style="width: 40vh" v-model="rolekw"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="!rolekw" @click="search">搜索</el-button>
        <el-button type="warning" @click="refresh">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 15px 0">
    <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table border stripe style="margin: 10px 0" :data="allRole">
      <el-table-column type="index" align="center" label="#" width="80px"></el-table-column>
      <el-table-column align="center" label="ID" width="80px" prop="id"></el-table-column>
      <el-table-column align="center" label="角色名称" width="200px" show-overflow-tooltip
                       prop="roleName"></el-table-column>
      <el-table-column align="center" label="创建时间" show-overflow-tooltip width="200px"
                       prop="createTime"></el-table-column>
      <el-table-column align="center" label="更新时间" show-overflow-tooltip width="200px"
                       prop="updateTime"></el-table-column>
      <el-table-column align="center" label="操作">
        <template #="{row}">
          <el-button type="primary" size="small" icon="User" @click="setPermission(row)">分配权限</el-button>
          <el-button type="warning" size="small" icon="Edit" @click="editRole(row)">编辑</el-button>
          <el-popconfirm width="250px" @confirm="deleteRole(row)" :title="`你确定要删除${row.roleName}?`">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination @current-change="getHasRole" @size-change="getHasRole(1)"
                   v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10,20,40]"
                   :background="true" layout="prev,pager,next,jumper,->,sizes,total" :total="total"/>
  </el-card>

  <!--添加职位与更新已有职位的结构:对话框-->
  <el-dialog v-model="dialogVis" :title="roleParams.id?'更新职位':'添加职位'" @close="closeDialog">
    <el-form :model="roleParams" :rules="rules" ref="FormVc">
      <el-form-item label="职位名称" prop="roleName">
        <el-input placeholder="请您输入角色名称" v-model="roleParams.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="dialogVis=false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>

  <!--抽屉：权限分配-->
  <el-drawer v-model="drawer">
    <template #header><h4>分配菜单与按钮的权限</h4></template>
    <template #default>
      <!--树形控件-->
      <el-tree :data="menuArr" :props="defaultProps" ref="TreeVc"
               show-checkbox node-key="id" default-expand-all :default-checked-keys="selectArr"/>
    </template>
    <template #footer>
      <el-button type="danger" @click="drawer=false">取消</el-button>
      <el-button type="primary" @click="handler">确定</el-button>
    </template>

  </el-drawer>


</template>

<script setup lang="ts">
import {ref, onMounted, reactive} from "vue";
//@ts-ignore
import type {T_MenuData, T_MenuResponseData, T_RoleData, T_RoleResponseData} from "@/api/acl/role/type.ts";
//@ts-ignore
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRoleList,
  reqRemoveRole,
  reqSetPermission
    //@ts-ignore
} from "@/api/acl/role/roleApi.ts";
import {ElMessage} from "element-plus";


//分页器
let pageNo = ref<number>(1);
let pageSize = ref<number>(10);
//存储职位数据
let allRole = ref<T_RoleData[]>([]);
let total = ref<number>(0);
let rolekw = ref<string>('');//用户输入搜索的关键字
//对话框
let dialogVis = ref<boolean>(false);
//收集新增岗位的数据
let roleParams = reactive<T_RoleData>({
  roleName: ''
})
//表单实例VC
let FormVc = ref<any>();
//抽屉
let drawer = ref<boolean>(false);
//定义数组存储用户权限的数据
let menuArr = ref<T_MenuData[]>([]);
//存储勾选节点的ID（四级的）
let selectArr = ref<number[]>([]);
//树形实例Vc
let TreeVc = ref<any>();


//组件挂在完毕，获取数据
onMounted(() => {
  getHasRole();

})

//获取职位数据
const getHasRole = async (pager: number = 1) => {
  pageNo.value = pager;
  let result: T_RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, rolekw.value);
  if (result.code == 200) {
    total.value = result.data.total;
    allRole.value = result.data.records;
  } else {
    ElMessage({type: "error", message: "获取职位信息失败！"});
  }
}

//搜索按钮的回调
const search = () => {
  //再次发送请求，关键字清空
  getHasRole();
  rolekw.value = '';
}

//重置按钮的回调
const refresh = () => window.location.reload();


//添加职位的回调
const addRole = () => {
  dialogVis.value = true;
}

//编辑职位按钮的回调
const editRole = (role: T_RoleData) => {
  //存储已有职位
  Object.assign(roleParams, role)
  dialogVis.value = true;
}

//自定义校验规则
//@ts-ignore
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error("职位名称至少两位"));
  }
}
//职位校验规则对象
const rules = {
  roleName: [{required: true, trigger: 'change', validator: validatorRoleName}]
}

//确定按钮的回调
const save = async () => {
  //进行表单校验
  await FormVc.value.validate();
  //添加职位/更新职位
  let result: any = await reqAddOrUpdateRole(roleParams);
  if (result.code == 200) {
    //提示的文字
    dialogVis.value = false;
    ElMessage({
      type: "success",
      message: roleParams.id ? `成功更新角色：${roleParams.roleName}` : `成功添加角色：${roleParams.roleName}`
    });
    getHasRole(roleParams.id ? pageNo.value : 1);//再获取职位信息
  } else {
    dialogVis.value = false;
    ElMessage({
      type: "error",
      message: roleParams.id ? `更新角色：${roleParams.roleName}失败` : `添加角色：${roleParams.roleName}失败`
    });
  }
}

//关闭dialog的回调
const closeDialog = () => {
  Object.assign(roleParams, {
    roleName: '',
    id: null
  });//初始化roleParam对象
  FormVc.value.resetFields();//清除校验信息
}

//分配权限按钮的回调
const setPermission = async (role: T_RoleData) => {
  drawer.value = true;
  //收集当前要分类权限的职位的数据
  Object.assign(roleParams, role);
  //根据职位获取权限的数据
  let result: T_MenuResponseData = await reqAllMenuList(roleParams.id);
  if (result.code == 200) {
    menuArr.value = result.data;
    selectArr.value = fillterSelectArr(menuArr.value, []);
  } else {
    //获取信息失败
    ElMessage({type: "error", message: "获取权限信息失败！"})
  }
}

const fillterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      fillterSelectArr(item.children, initArr);
    }
  })
  return initArr;
}

//树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}

//抽屉确定按钮 下发权限的确定按键
const handler = async () => {
  //职位的id
  const roleId = roleParams.id;
  //选中节点的id
  let arr1 = TreeVc.value.getCheckedKeys();//选中的id
  let arr2 = TreeVc.value.getHalfCheckedKeys();//半选的id
  let permissionId = arr1.concat(arr2);
  //发送请求
  let result: any = await reqSetPermission(roleId, permissionId);
  if (result.code == 200) {
    ElMessage({type: "success", message: `${roleParams.roleName}下发权限成功！`});
  } else {
    ElMessage({type: "error", message: `${roleParams.roleName}下发权限失败！`});
  }
  drawer.value = false;
  window.location.reload();
}


//删除角色按钮回调
const deleteRole = async (role: T_RoleData) => {
  let result: any = await reqRemoveRole(role.id);
  if (result.code == 200) {
    ElMessage({type: "success", message: `成功删除${role.roleName}`});
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);//重新获取信息
  } else {
    ElMessage({type: "error", message: `删除${role.roleName}失败！`});
  }
}
</script>


<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>